<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------


namespace app\adminapi\controller;


use app\adminapi\controller\BaseAdminController;
use app\adminapi\lists\CardLists;
use app\adminapi\logic\CardLogic;
use app\adminapi\validate\CardValidate;
use app\common\exception\AppLogicException;
use app\common\model\Card;
use app\common\model\Merchant;
use app\common\model\user\User;
use app\common\service\ConfigService;
use app\common\service\ExcelImporter;
use app\common\service\UploadService;
use PhpOffice\PhpSpreadsheet\Exception;
use think\db\Query;
use think\facade\Config;


/**
 * Card控制器
 * Class CardController
 * @package app\adminapi\controller
 */
class CardController extends BaseAdminController
{


    /**
     * @notes 获取列表
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/02/24 14:37
     */
    public function lists()
    {
        return $this->dataLists(new CardLists());
    }


    /**
     * @notes 添加
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/02/24 14:37
     */
    public function add()
    {
        $params = (new CardValidate())->post()->goCheck('add');
        $result = CardLogic::add($params);
        if (true === $result) {
            return $this->success('添加成功', [], 1, 1);
        }
        return $this->fail(CardLogic::getError());
    }


    /**
     * @notes 删除
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/02/24 14:37
     */
    public function delete()
    {
        $params = (new CardValidate())->post()->goCheck('delete');
        CardLogic::delete($params);
        return $this->success('删除成功', [], 1, 1);
    }


    /**
     * @notes 获取详情
     * @return \think\response\Json
     * @author likeadmin
     * @date 2025/02/24 14:37
     */
    public function detail()
    {
        $params = (new CardValidate())->goCheck('detail');
        $result = CardLogic::detail($params);
        return $this->data($result);
    }

    public function import()
    {
        $headerMapping = [
            'titles' => [
                '手机号',
                '姓名'
            ],
            'fields' => [
                '手机号' => ['mobile'],
                '姓名'   => ['name']
            ]
        ];
        // 上传文件
        $result = UploadService::file(0);

        $filePath = $result['url'];

        // 创建 ExcelImporter 实例

        try {
            $excelImporter = new ExcelImporter($filePath);// 设置标题映射
            $excelImporter->setHeaderMapping($headerMapping);// 解析 Excel 数据
            $data = $excelImporter->parse();
        } catch (Exception $e) {
            return $this->fail($e->getMessage());
        } catch (AppLogicException $e) {
            return $this->fail($e->getMessage());
        }
        $importData = [
            'normal' => $data,
            'error'  => []
        ];
        // 处理数据


        return $this->data($importData);
    }


    public function batchAdd()
    {
        $params = $this->request->post();

        /**
         * @var Merchant $merchant
         */
        $merchant = Merchant::where('id', $params['merchant_id'])->find();
        if (!$merchant) {
            return $this->fail('商户不存在');
        }

        collect($params['userList'])->each(function ($item) use ($params, $merchant) {
            $userSn = User::createUserSn();
            $avatar = ConfigService::get('default_image', 'user_avatar');
            /**
             * @var User $user
             */
            $user =   User::where('mobile',$item['mobile'])->find();
            if(!$user){
                $user = new User();
                $user->mobile = $item['mobile'];
                $user->account = $item['mobile'];
                $user->avatar = $avatar;
                $user->sn = $userSn;
                $user->nickname = $item['name'];
                $user->save();
            }
            // 生成用户
            $userId = $user->id;
            // 生成卡密
            $product_type_id_arr = $params['product_type_id_arr'];
            $card = new Card();
            $card->account = generate_sn(Card::class, 'account');
            $card->merchant_id = $params['merchant_id'];
            $card->product_id = json_encode($product_type_id_arr) ;
            $card->user_id = $userId;
            $card->card_type = $merchant->type;
            $card->save();
        });
        return $this->success('导入成功', [], 1, 1);
    }


}